<template>
  <div class="app-container">
    <!-- 页面标题和标签页 -->
    <div class="page-header">
      <h2 class="page-title">商品清单</h2>
      <div class="tabs">
        <div
          class="tab-item"
          :class="{ active: activeTab === 'onSale' }"
          @click="activeTab = 'onSale'"
        >
          上架中 ({{ onSaleCount }})
        </div>
        <div
          class="tab-item"
          :class="{ active: activeTab === 'warehouse' }"
          @click="activeTab = 'warehouse'"
        >
          仓库中 ({{ warehouseCount }})
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <!-- 售罄筛选（仅在仓库中显示） -->
        <el-form-item v-if="activeTab === 'warehouse'" label="">
          <el-select
            v-model="searchForm.isSoldOut"
            placeholder="请选择售罄中商品"
            clearable
            @change="handleSearch"
          >
            <el-option label="售罄中商品" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select
            v-model="searchForm.categoryId1"
            placeholder="一级分类"
            clearable
          >
            <el-option
              v-for="item in category1List"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="searchForm.categoryId2"
            placeholder="二级分类"
            clearable
          >
            <el-option
              v-for="item in category2List"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 批量操作区域 -->
    <div class="batch-actions">
      <el-checkbox v-model="selectAll" @change="handleSelectAll"
        >全选</el-checkbox
      >
      <el-button
        type="default"
        :disabled="selectedItems.length === 0"
        @click="handleBatchOnSale"
      >
        批量上架
      </el-button>
      <el-button
        type="default"
        :disabled="selectedItems.length === 0"
        @click="handleBatchOffSale"
      >
        批量下架
      </el-button>
      <el-button
        type="default"
        :disabled="selectedItems.length === 0"
        @click="handleBatchModifyCategory"
      >
        批量修改分类
      </el-button>
    </div>

    <!-- 商品列表表格 -->
    <el-table
      ref="productTable"
      :data="productList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      class="product-table"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="商品ID" width="80" />
      <el-table-column prop="display_order" label="排序" width="80" />
      <el-table-column label="商品图片" width="100">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.thumb"
            :preview-src-list="[scope.row.thumb]"
            class="product-thumb"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="商品名称"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column label="价格" width="120">
        <template slot-scope="scope">
          <span class="price">¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.stock }}</span>
          <el-button
            type="text"
            size="mini"
            @click="handleEditStock(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="total_sales" label="销量" width="100" />
      <el-table-column label="上下架状态" width="120">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
          <span class="status-text">{{
            scope.row.status ? "上架" : "下架"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 编辑库存对话框 -->
    <el-dialog
      title="编辑库存"
      :visible.sync="stockDialogVisible"
      width="400px"
    >
      <el-form :model="stockForm" label-width="80px">
        <el-form-item label="当前库存">
          <el-input-number v-model="stockForm.stock" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveStock">确定</el-button>
      </div>
    </el-dialog>

    <!-- 批量修改分类对话框 -->
    <el-dialog
      title="批量修改分类"
      :visible.sync="categoryDialogVisible"
      width="500px"
    >
      <el-form :model="categoryForm" label-width="100px">
        <el-form-item label="一级分类">
          <el-select
            v-model="categoryForm.categoryId1"
            placeholder="请选择一级分类"
          >
            <el-option
              v-for="item in category1List"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select
            v-model="categoryForm.categoryId2"
            placeholder="请选择二级分类"
          >
            <el-option
              v-for="item in category2ListForDialog"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProductList,
  updateProduct,
  batchUpdateProduct,
  fetchList
} from "@/api/product";

export default {
  name: "ProductList",
  data() {
    return {
      activeTab: "onSale",
      loading: false,
      selectAll: false,
      selectedItems: [],
      productList: [],
      onSaleCount: 0,
      warehouseCount: 0,

      // 搜索表单
      searchForm: {
        title: "",
        categoryId1: "",
        categoryId2: "",
        status: 1,
        isSoldOut: "" // 是否售罄（库存为0）
      },

      // 分页
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },

      // 分类数据
      category1List: [],
      category2List: [],
      category2ListForDialog: [], // 弹框中的二级分类

      // 编辑库存对话框
      stockDialogVisible: false,
      stockForm: {
        id: null,
        stock: 0
      },

      // 批量修改分类对话框
      categoryDialogVisible: false,
      categoryForm: {
        categoryId1: "",
        categoryId2: ""
      }
    };
  },

  created() {
    this.loadProductList();
    this.loadCategories();
  },

  watch: {
    // 监听一级分类变化，加载对应的二级分类
    "searchForm.categoryId1"(newVal) {
      this.searchForm.categoryId2 = ""; // 清空二级分类
      if (newVal) {
        this.loadCategory2List(newVal);
      } else {
        this.category2List = [];
      }
    },
    // 监听批量修改分类弹框中的一级分类变化
    "categoryForm.categoryId1"(newVal) {
      this.categoryForm.categoryId2 = ""; // 清空二级分类
      if (newVal) {
        this.loadCategory2ListForDialog(newVal);
      } else {
        this.category2ListForDialog = [];
      }
    },
    // 监听标签页切换
    activeTab(newVal) {
      this.searchForm.status = newVal === "onSale" ? 1 : 0;
      this.searchForm.isSoldOut = ""; // 切换标签页时清空售罄筛选
      this.pagination.page = 1;
      this.loadProductList();
    }
  },

  methods: {
    // 加载商品列表
    async loadProductList() {
      this.loading = true;
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit,
          title: this.searchForm.title,
          status: this.searchForm.status
        };

        // 优先使用二级分类，如果没有二级分类则使用一级分类
        if (this.searchForm.categoryId2) {
          params.categoryId = this.searchForm.categoryId2;
        } else if (this.searchForm.categoryId1) {
          params.categoryId = this.searchForm.categoryId1;
        }

        // 如果选择了售罄中商品筛选
        if (this.searchForm.isSoldOut === 1) {
          params.isSoldOut = 1;
        }

        const response = await getProductList(params);
        this.productList = response.data.list;
        this.pagination.total = response.data.total;

        // 使用后端返回的统计数据
        if (response.data.stats) {
          this.onSaleCount = response.data.stats.online_count || 0;
          this.warehouseCount = response.data.stats.offline_count || 0;
        } else {
          // 兼容旧版本API，如果没有stats字段则使用原来的逻辑
          this.onSaleCount = response.data.onSaleCount || 0;
          this.warehouseCount = response.data.warehouseCount || 0;
        }
      } catch (error) {
        this.$message.error("加载商品列表失败");
      } finally {
        this.loading = false;
      }
    },

    // 加载一级分类数据
    async loadCategories() {
      try {
        const response = await fetchList({ level: 1 });
        if (response.code == 200) {
          this.category1List = response.data.list || [];
        } else {
          this.$message.error(response.msg || "加载分类失败");
        }
      } catch (error) {
        console.error("加载分类失败", error);
        this.$message.error("加载分类失败");
      }
    },

    // 加载二级分类数据
    async loadCategory2List(parentId) {
      try {
        const response = await fetchList({ level: 2, parent_id: parentId });
        if (response.code == 200) {
          this.category2List = response.data.list || [];
        } else {
          this.$message.error(response.msg || "加载二级分类失败");
        }
      } catch (error) {
        console.error("加载二级分类失败", error);
        this.$message.error("加载二级分类失败");
      }
    },

    // 加载弹框中的二级分类数据
    async loadCategory2ListForDialog(parentId) {
      try {
        const response = await fetchList({ level: 2, parent_id: parentId });
        if (response.code == 200) {
          this.category2ListForDialog = response.data.list || [];
        } else {
          this.$message.error(response.msg || "加载二级分类失败");
        }
      } catch (error) {
        console.error("加载二级分类失败", error);
        this.$message.error("加载二级分类失败");
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1;
      this.loadProductList();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        title: "",
        categoryId1: "",
        categoryId2: "",
        status: this.activeTab === "onSale" ? 1 : 0,
        isSoldOut: ""
      };
      this.category2List = [];
      this.handleSearch();
    },

    // 全选
    handleSelectAll(val) {
      if (val) {
        // 全选
        this.productList.forEach(row => {
          this.$refs.productTable.toggleRowSelection(row, true);
        });
      } else {
        // 取消全选
        this.$refs.productTable.clearSelection();
      }
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedItems = selection;
      this.selectAll =
        selection.length > 0 && selection.length === this.productList.length;
    },

    // 批量上架
    async handleBatchOnSale() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请选择要上架的商品");
        return;
      }

      try {
        const ids = this.selectedItems.map(item => item.id);
        await batchUpdateProduct({ ids, status: 1 });
        this.$message.success("批量上架成功");
        this.loadProductList();
      } catch (error) {
        this.$message.error("批量上架失败");
      }
    },

    // 批量下架
    async handleBatchOffSale() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请选择要下架的商品");
        return;
      }

      try {
        const ids = this.selectedItems.map(item => item.id);
        await batchUpdateProduct({ ids, status: 0 });
        this.$message.success("批量下架成功");
        this.loadProductList();
      } catch (error) {
        this.$message.error("批量下架失败");
      }
    },

    // 批量修改分类
    handleBatchModifyCategory() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请选择要修改分类的商品");
        return;
      }
      // 重置分类表单
      this.categoryForm = {
        categoryId1: "",
        categoryId2: ""
      };
      // 清空弹框中的二级分类
      this.category2ListForDialog = [];
      this.categoryDialogVisible = true;
    },

    // 保存分类修改
    async handleSaveCategory() {
      try {
        const ids = this.selectedItems.map(item => item.id);
        await batchUpdateProduct({
          ids,
          category_id_1: this.categoryForm.categoryId1,
          category_id_2: this.categoryForm.categoryId2
        });
        this.$message.success("批量修改分类成功");
        this.categoryDialogVisible = false;
        this.loadProductList();
      } catch (error) {
        this.$message.error("批量修改分类失败");
      }
    },

    // 编辑库存
    handleEditStock(row) {
      this.stockForm = {
        id: row.id,
        stock: row.stock
      };
      this.stockDialogVisible = true;
    },

    // 保存库存
    async handleSaveStock() {
      try {
        await updateProduct(this.stockForm.id, { stock: this.stockForm.stock });
        this.$message.success("库存更新成功");
        this.stockDialogVisible = false;
        this.loadProductList();
      } catch (error) {
        this.$message.error("库存更新失败");
      }
    },

    // 状态变化
    async handleStatusChange(row) {
      try {
        await updateProduct(row.id, { status: row.status });
        this.$message.success("状态更新成功");
      } catch (error) {
        this.$message.error("状态更新失败");
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1;
      }
    },

    // 编辑商品
    handleEdit(row) {
      console.log(row);
      this.$router.push({
        name: "updateProduct",
        query: {
          id: row.id
        }
      });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.limit = val;
      this.pagination.page = 1;
      this.loadProductList();
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.loadProductList();
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 16px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
}

.tab-item {
  padding: 12px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  color: #606266;
}

.tab-item.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

.filter-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.batch-actions {
  background: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-thumb {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.status-text {
  margin-left: 8px;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
